package cn._2dland.net
{
	import cn._2dland.utils.CommentUtils;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	[Event(name="complete", type="flash.events.Event")]
	[Event(name="error", type="flash.events.ErrorEvent")]	

	public class CommentLoader extends EventDispatcher
	{
		private static const COMMENT_URL:String = "/watch/load_comment.php";
		private static const FULL_COMMENT_URL:String = "http://www.2dland.cn/watch/load_comment.php";

		private var _loader:URLLoader = null;
		private var _commentXML:XML = null;

		public function CommentLoader() { }

		public function load(vid:String, remote:Boolean=false):void {
			if(_loader == null) init();

			var url:String = remote ? FULL_COMMENT_URL : COMMENT_URL;
			url += "?vid=" + vid + "&max=" + CommentUtils.MAX_COMMENT_COUNT + "&baka=" + Math.random();
			_loader.load(new URLRequest(url));
		}

		public function get commentXML():XML {
			return _commentXML;
		}

		private function init():void {
			if(_loader != null) return;
			_loader = new URLLoader();
			_loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_loader.addEventListener(Event.COMPLETE, completeHandler);
		}

		private function release():void {
			if(_loader == null) return;

			_loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_loader.removeEventListener(Event.COMPLETE, completeHandler);
			try{ _loader.close(); }
			catch(err:Error){ trace(err.message); }
			_loader = null;
		}

		protected function ioErrorHandler(e:IOErrorEvent):void {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, e.text));
			release();
		}

		protected function completeHandler(e:Event):void {
			_commentXML = new XML(_loader.data);
			dispatchEvent(new Event(Event.COMPLETE));
			release();
		}
	}
}